package com.twotiger.and.web;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.webkit.WebView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.activity.HomeActivity;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.project.ProjectDetailPage;
import com.twotiger.and.activity.project.debt.ProjectDebtDetailPage;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.bean.Share;
import com.twotiger.and.bean.User;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.UpdateVersionUtil;

/**
 * 被JS调用的方法
 * @author douxu
 *
 */
public class JavaScriptInterface {
    protected static final int LOGINSUCCES = 0;
    protected static final int LOGINFAIL = 1;
    private Activity mcontext;
    private WebView mwebView;
    private BaseHandler mHandler;

    public static String name() {
        return "_TT";
    }

    public JavaScriptInterface(WebView webView, Activity context, BaseHandler handler) {
        super();
        mwebView = webView;
        mcontext = context;
        mHandler = handler;
    }

    /**
     * 注册成功页面，点击先逛逛
     */
    public void firstLook() {
        ((BaseActivity) mcontext).startNewActivity(new Intent(mcontext, HomeActivity.class),
            R.anim.push_left_in, R.anim.push_left_out, true);
    }

    /**
     * 注册成功页面，点击开通托管
     */
    public void registHF() {
        ((WebViewPage) mcontext).isFinish = true;
        ((WebViewPage) mcontext).openpayment();
    }

    /**
     * 进入注册页面
     */
    public void toRegist() {
        //        Intent intent1 = new Intent(mcontext, RegisterPage.class);
        //        ((WebViewPage) mcontext).startNewActivity(intent1, R.anim.slide_in_from_bottom,
        //            R.anim.silent_anim, false);
        Intent intent1 = new Intent(mcontext, LoginPage.class);
        intent1.putExtra("witchLayout", "regist");
        ((WebViewPage) mcontext).startNewActivity(intent1, R.anim.slide_in_from_bottom,
            R.anim.silent_anim, false);
    }

    /**
     * 进入登录页面
     */
    public void toLogin() {
        Intent intent2 = new Intent(mcontext, LoginPage.class);
        ((WebViewPage) mcontext).startNewActivity(intent2, R.anim.slide_in_from_bottom,
            R.anim.silent_anim, false);
        ((WebViewPage) mcontext).application.setNeedReload(true); //设为true，回来的时候就会reload页面了
    }

    /**
     * 进入精选、项目列表、我的钱、更多
     * @param tag  0-精选  1-项目列表（直投）   2-我的钱   3-更多 4-活期  5-项目列表（转让） 6- 活期转入（未登录则进弹框） 7-在线客服
     */
    public void toPage(int tag) {
        switch (tag) {
        case 0:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_BOUTIQUEPAGE);
            break;
        case 1:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_PROJECTEPAGE);
            break;
        case 2:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_ACCOUNTEPAGE);
            break;
        case 3:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_MOREPAGE);
            break;
        case 4:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_CURRENTPAGE);
            break;
        case 5:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_PROJECTEPAGE_TRANS);
            break;
        case 6:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_CURRENT_ENTER);
            break;
        case 7:
            mHandler.sendEmptyMessage(WebViewPage.GOTO_CHATPAGE);
            break;
        default:
            break;
        }
    }

    /**
     * 进入某个项目的详情页面（直投项目）
     * 
     * @param projectId   
     * @param mode   
     */
    public void toProjectDetail(String type, String mode, String projectId) {
        if (Constants.TYPE_NID_ZHITOU.equals(type)) {
            Intent intent = new Intent(mcontext, ProjectDetailPage.class).putExtra("PROJECT_ID",
                projectId).putExtra("MODE", mode);
            ((WebViewPage) mcontext).startNewActivity(intent, R.anim.push_left_in,
                R.anim.push_left_out, false);
        } else if (Constants.TYPE_NID_HEIDONG.equals(type)) {
        }
    }

    /**
     * 进入某个项目的详情页面（转让项目）
     * 
     * @param projectId   
     * @param mode   
     */
    public void toBondProjectDetail(String bid) {
        Intent intent = new Intent(mcontext, ProjectDebtDetailPage.class).putExtra(
            "DEBT_TRANS_MARK", bid);
        ((WebViewPage) mcontext).startNewActivity(intent, R.anim.push_left_in,
            R.anim.push_left_out, false);
    }

    /**
     * 进入某个项目的投资页面
     * 
     * @param projectId
     * @param mode
     */
    public void toProjectInvest(String type, String mode, String projectId) {
        //由于投资页面需要对应的信息，故先请求网络拿到项目的详情信息
        ((WebViewPage) mcontext).getProjectDetail(type, mode, projectId);
    }

    /**
     * 进入某个项目的投资页面
     * 
     * @param projectId
     * @param mode
     */
    public void toBondProjectInvest(String bid) {
        //由于投资页面需要对应的信息，故先请求网络拿到项目的详情信息
        ((WebViewPage) mcontext).getDebtProjectDetail(bid);
    }

    /**
     * 获取分享参数,预分享！！   跟及时分享区分
     * @return
     */
    public void appShare(String title, String cont, String url, String img) {

        Share mShare = new Share();
        mShare.setTitle(title);
        mShare.setContent(cont);
        mShare.setUrl(url);
        mShare.setPic(img);

        Message msg = Message.obtain();
        msg.what = WebViewPage.TO_SHARE_PRE;
        msg.obj = mShare;
        mHandler.sendMessage(msg);
    }

    /**
     * 
     * 调用分享功能        ！！！及时分享
     * @param url    
     * @param title
     * @param cont
     * @param img
     */
    public void toShare(String title, String cont, String url, String img) {

        Share mShare = new Share();
        mShare.setTitle(title);
        mShare.setContent(cont);
        mShare.setUrl(url);
        mShare.setPic(img);

        Message msg = Message.obtain();
        msg.what = WebViewPage.TO_SHARE;
        msg.obj = mShare;
        mHandler.sendMessage(msg);
    }

    /**
     * 2.8版本分享
     * 
     * @param title
     * @param cont
     * @param url
     * @param img
     * @param channel  分享渠道（weixin:微信、朋友圈；all：所有）
     */
    public void toShareChannel(String title, String cont, String url, String img, String channel) {

        Share mShare = new Share();
        mShare.setTitle(title);
        mShare.setContent(cont);
        mShare.setUrl(url);
        mShare.setPic(img);
        mShare.setChannel(channel);

        Message msg = Message.obtain();
        msg.what = WebViewPage.TO_SHARE_CHANNEL;
        msg.obj = mShare;
        mHandler.sendMessage(msg);
    }

    /**
     * 
     * 下载新的apk
     * @param url    
     */
    public void appDown(String versionCode, String url) {
        if (Integer.parseInt(versionCode) > PackageUtils.getAppVersionCode(mcontext)) {
            UpdateVersionUtil.ShowUpAppDialog(mcontext, url);
        } else {
            ((WebViewPage) mcontext).showToast("您的当前版本已经是最新版");
        }
    }

    /**
     * 获取用户信息
     * @return
     */
    public void userInfo() {
        User user = null;
        if (((WebViewPage) mcontext).isLogin()) {
            user = TwoTigerApp.getInstance().getUser();
        }
        final HashMap<String, String> hashMap = new HashMap<String, String>();
        if (user != null) {
            hashMap.put("name", user.name);
            hashMap.put("phone", user.phone);
            hashMap.put("thirdAccount", user.thirdAccountName);
            hashMap.put("token", ((WebViewPage) mcontext).getToken()); //用户信息增加token
        } else {
            hashMap.put("name", "");
            hashMap.put("phone", "");
            hashMap.put("thirdAccount", "");
            hashMap.put("token", "");
        }
        mwebView.post(new Runnable() {
            @Override
            public void run() {
                String format = String.format("javascript:userInfoCallBack("
                                              + JSONObject.toJSONString(hashMap).toString() + ")");
                mwebView.loadUrl(format);

            }
        });
    };

    /**
     * 获取用户信息
     * @return
     */
    public void exchangeQuan(String caId) {

        Message msg = Message.obtain();
        msg.what = WebViewPage.TO_CHANGE_COUPON;
        msg.obj = caId;
        mHandler.sendMessage(msg);
    };

    /**
     * 获取用户信息
     * @return
     */
    public void sysBrowser(String url) {
        Message msg = Message.obtain();
        msg.what = WebViewPage.TO_SYSBROWSER;
        msg.obj = url;
        mHandler.sendMessage(msg);
    };

    /*public void logout() {
        Intent intent = new Intent(mcontext, LoginPage.class);
        intent.putExtra("logoutfromjs", true);
        mcontext.startActivity(intent);
    };

    public void getUserStatus() {
        final String islogin = (TwoTigerApp.getInstance().getUser() != null) ? "1" : "0";
        mwebView.post(new Runnable() {
            @Override
            public void run() {
                mwebView.loadUrl("javascript:getUserStatus(" + islogin + ")");
            }
        });
    }

    public void getNetinfo() {
        //1是有网络0是无网络
        HashMap<String, String> hashMap = new HashMap<String, String>();
        if (NetWorkUtil.isNetworkConnected(mcontext)) {
            hashMap.put("status", "1");
            hashMap.put("type", NetWorkUtil.getNetTypeName(mcontext));
        } else {
            hashMap.put("status", "0");
        }

        final String jsonString = JSONObject.toJSONString(hashMap);
        mwebView.post(new Runnable() {

            @Override
            public void run() {
                String format = String.format("javascript:getNetinfo(" + jsonString + ")");
                mwebView.loadUrl(format);
            }
        });

    };

    public void toProDetail(String pid) {
        Intent intent = new Intent(mcontext, ProjectDetailPage.class).putExtra("id", pid);// 
        mcontext.startActivity(intent);
        mcontext.finish();
    };*/
}
